package cmsc427.mw5;
import java.util.Queue;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/*
 * A sample window - the number of readings to be considered at one time
 * for the machine learning algorithm.  The Add() method also sends the 
 * window to the machine learning algorithm after 'testInterval' readings
 * have been added.
 */
public class SampleWindow {

	public Queue<AccelerometerReading> readingsWindow;
	private int sampleWindowSize;
	private int testInterval;
	private int inputCount;
	public static float X_filt = 0;
	public static float Y_filt = 0;
	public static float Z_filt = 0;

	SampleWindow(){
		this.sampleWindowSize = 100;
		this.testInterval = 100;
		this.inputCount = 0;
		this.readingsWindow = new LinkedList<AccelerometerReading>();
		
		//initialize the sample window
		for(int i=0; i < sampleWindowSize; i++){
			readingsWindow.add(new AccelerometerReading(0,0,0) );
		}
	}
	
	/**
	 * Add an accelerometer reading to the Queue, and remove the first
	 * entry.  If 'testInterval' number of entries have been added, the
	 * readings window is sent for gesture recognition testing.
	 * @param input
	 */
	public String Add(String input, TrainingSet tSet){
		String output = "unknown";
		
		//keep menu strings from the accelerometer from making their way here
		if(input.contains("X=")){
			
			//remove the oldest reading
			readingsWindow.remove();
			
			//insert the newest reading
			readingsWindow.add( sampleFromString(input) );			
			
			inputCount++;
			if(inputCount == testInterval){
				inputCount = 0;
				 
				//send readingsWindow to the ml classifier
				output = GestureGuess.checkWindow(this, tSet);
			}
		}
		return output;
	}
	
	//extract x,y,z values from a string
	private AccelerometerReading sampleFromString(String input){
		Pattern pattern = Pattern.compile("(\\d+)");
		Matcher result = pattern.matcher(input);
		float X;
		float Y;
		float Z;
		
		if( result.find() ){
			X = Float.parseFloat( input.substring(result.start(), result.end()) );
			if(result.find()){
				Y = Float.parseFloat( input.substring(result.start(), result.end()) );
				if(result.find()){
					Z = Float.parseFloat( input.substring(result.start(), result.end()) );
					X_filt = ((X_filt*0.8f)+(X*0.2f));
					Y_filt = ((Y_filt*0.8f)+(Y*0.2f));
					Z_filt = ((Z_filt*0.8f)+(Z*0.2f));
					
					return new AccelerometerReading(X_filt,Y_filt,Z_filt);
				}
			}
		}
	    return new AccelerometerReading(0,0,0);
	}
	
	public int getSampleSize(){
		return this.sampleWindowSize;
	}
}
